package com.le.buddha.conf;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.le.buddha.common.BusinessRuntimeException;
import com.le.buddha.common.ResultCode;
import com.le.buddha.mobile.User;
import com.le.buddha.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 用户请求拦截器
 */
@Configuration
@Slf4j
public class AppInterceptor implements HandlerInterceptor {

    @Resource
    public IUserService userService;
    @Resource
    private RedisTemplate template;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        String url = request.getRequestURI();
        String token = request.getHeader("TOKEN_USER");

        if (ArrayUtil.contains(NO_AUTHORIZATION_URL, url)) {
            return true;
        }



        if (StrUtil.isEmpty(token)) {
            throw new BusinessRuntimeException(  ResultCode.NOT_LOGIN);

        }
         if (!template.hasKey(RedisKey.userToken + token)) {
            //reids中找不到token就从数据库中找
            User user = userService.lambdaQuery().eq(User::getStatus, 1).eq(User::getToken, token).one();

            if (ObjectUtil.isNull(user)) {

                throw new BusinessRuntimeException(  ResultCode.NOT_LOGIN);
            }
             template.opsForValue().set(RedisKey.userToken + token, user.getId(), 1, TimeUnit.DAYS);
         }


        return true;
    }



    private String[] NO_AUTHORIZATION_URL = new String[]{"/app/wechat/updateMenu",
            "/app/user/sendCaptcha", "/app/user/login", "/app/user/register","/app/buddhaRole/buddhaRoleList"
            ,"/app/user/registerAndLogin","/app/user/getOpenId"

    };

}